﻿using System;
using System.Data;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using System.Windows.Forms;

namespace BaiduMapPOI
{
    
    public partial class MainForm : Form
    {
        SqlOP sqlOP = new SqlOP(BaiduMapPOI.Properties.Settings.Default.conn);
        MysqlOP mysqlOP = new MysqlOP();
        string startX = "";
        string startY = "";
        string endX = "";
        string endY = "";
        int id = 0;
        int k = 1;
        WebBrowser getWeb;
        DataTable dtColor;

        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            startX = BaiduMapPOI.Properties.Settings.Default.startX;
            startY = BaiduMapPOI.Properties.Settings.Default.startY;
            endX = BaiduMapPOI.Properties.Settings.Default.endX;
            endY = BaiduMapPOI.Properties.Settings.Default.endY;

            if (!StringProcess.IsNullOrEmpty(startX))
                this.txtStartX.Text = startX;

            if (!StringProcess.IsNullOrEmpty(startY))
                this.txtStartY.Text = startY;

            if (!StringProcess.IsNullOrEmpty(endX))
                this.txtEndX.Text = endX;

            if (!StringProcess.IsNullOrEmpty(endY))
                this.txtEndY.Text = endY;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            startX = this.txtStartX.Text;
            startY = this.txtStartY.Text;
            endX = this.txtEndX.Text;
            endY = this.txtEndY.Text;

            if (!StringProcess.IsNullOrEmpty(startX))
                BaiduMapPOI.Properties.Settings.Default.startX = startX;

            if (!StringProcess.IsNullOrEmpty(startY))
                BaiduMapPOI.Properties.Settings.Default.startY = startY;

            if (!StringProcess.IsNullOrEmpty(endX))
                BaiduMapPOI.Properties.Settings.Default.endX = endX;

            if (!StringProcess.IsNullOrEmpty(endY))
                BaiduMapPOI.Properties.Settings.Default.endY = endY;

            BaiduMapPOI.Properties.Settings.Default.Save();
            MessageBox.Show("起止坐标保存成功！");
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            this.btnOK.Enabled = false;
            Thread thread = new Thread(new ThreadStart(Begin));
            thread.Start();
        }


        private void btnReQuery_Click(object sender, EventArgs e)
        {
            if (sqlOP.db.State != ConnectionState.Open)
            {
                sqlOP.db.Open();
            }

            DataTable dtErrorPoint = sqlOP.Select("id,x,y", "log", "");

            foreach (DataRow dr in dtErrorPoint.Rows)
            {
                string errorPointX = dr["x"].ToString();
                string errorPointY = dr["Y"].ToString();
                string urlError = "http://api.map.baidu.com/?qt=rgc&x=" + errorPointX + "&y=" + errorPointY + "&dis_poi=100&poi_num=500&fromproduct=jsapi";

                try
                {
                    this.BeginInvoke((MethodInvoker)delegate()
                    {
                        this.liMessage.Items.Add("当前摩卡托坐标:" + errorPointX + ";" + errorPointY);
                    });

                    AddInfo(urlError);
                    sqlOP.Insert("x,y", "point", "'" + errorPointX + "','" + errorPointY + "'");
                    sqlOP.Delete("log", "(id = " + dr["id"].ToString() + ")");
                }
                catch (Exception ex)
                {
                    sqlOP.Insert("x,y,cause,time", "log", "'" + errorPointX + "','" + errorPointY + "','" + ex.ToString() + "','" + DateTime.Now.ToString() + "'");
                }
            }

            MessageBox.Show("遗漏数据添加成功！");
            sqlOP.db.Close();
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            sqlOP.db.Close();
            System.Environment.Exit(System.Environment.ExitCode);
            this.Dispose();
            this.Close();
        }

        void Begin()
        {
            sqlOP.db.Open();

            DataTable dt = sqlOP.GetMax("x", "point", "x");

            if (StringProcess.IsNullOrEmpty(dt.Rows[0]["x"].ToString()))
            {
                Start(Convert.ToDouble(startX), Convert.ToDouble(startY), Convert.ToDouble(endX), Convert.ToDouble(endY), Convert.ToDouble(startX));
            }
            else
            {
                Start(Convert.ToDouble(startX), Convert.ToDouble(startY), Convert.ToDouble(endX), Convert.ToDouble(endY), Convert.ToDouble(dt.Rows[0]["x"].ToString()));
            }
        }

        void Start(double sX, double sY, double eX, double eY, double cX)
        {
            double x = sX;
            double step = Convert.ToDouble(this.txtStep.Text);

            do
            {
                double y = sY;

                do
                {
                    Query(x, y, cX);
                    //Thread.Sleep(2000);
                    y += step;
                } while (y <= eY);

                x += step;
            } while (x <= eX);

            this.BeginInvoke((MethodInvoker)delegate()
            {
                MessageBox.Show("信息采集完成！");
                this.btnOK.Enabled = true;
            });
        }

        void Query(double x, double y, double cX)
        {
            if (x >= cX)
            {
                string url = "http://api.map.baidu.com/?qt=rgc&x=" + x.ToString() + "&y=" + y.ToString() + "&dis_poi=100&poi_num=500&fromproduct=jsapi";

                try
                {
                    this.BeginInvoke((MethodInvoker)delegate()
                    {
                        this.liMessage.Items.Add("当前摩卡托坐标:" + x.ToString() + ";" + y.ToString());
                    });

                    AddInfo(url);
                    //存储当前摩卡托坐标值
                    sqlOP.Insert("x,y", "point", "'" + x + "','" + y + "'");
                }
                catch (Exception ex)
                {
                    sqlOP.Insert("x,y,cause,time", "log", "'" + x.ToString() + "','" + y.ToString() + "','" + ex.ToString() + "','" + DateTime.Now.ToString() + "'");
                }
            }
        }

        void AddInfo(string url)
        {
            string info = StringProcess.GetResult(url, Encoding.UTF8).Replace("\"", "").Replace("\\", "");
            //获取中心点信息
            string content = Regex.Match(info, "(?<=(address_detail:{))[\\S\\s]*?(?=(,surround_poi))").Value;
            string city = Regex.Match(content, "(?<=(city:))[\\S\\s]*?(?=(,))").Value;
            string district = Regex.Match(content, "(?<=(district:))[\\S\\s]*?(?=(,))").Value;
            string street = Regex.Match(content, "(?<=(street:))[\\S\\s]*?(?=(,))").Value;
            string street_number = Regex.Match(content, "(?<=(street_number:))[\\S\\s]*?(?=(},))").Value;
            string business = Regex.Match(content, "(?<=(business:))[\\S\\s]*?(?=(,point))").Value;
            string cX = Regex.Match(content, "(?<=(x:))[\\S\\s]*?(?=(,))").Value;
            string cY = Regex.Match(content, "(?<=(,y:))[\\S\\s]*?(?=(}))").Value;

            //获取半径为100米内信息
            string list = Regex.Match(info, "(?<=(\\[))[\\S\\s]*?(?=(\\]))").Value + ",{";
            MatchCollection mcList = Regex.Matches(list, "(?<=({))[\\S\\s]*?(?=(},{))");

            for (int i = 0; i < mcList.Count; i++)
            {
                string sList = mcList[i].ToString().Replace("\\", "");
                string name = Regex.Match(sList, "(?<=(name:))[\\S\\s]*?(?=(,))").Value;
                string address = Regex.Match(sList, "(?<=(addr:))[\\S\\s]*?(?=(,))").Value;
                string tel = Regex.Match(sList, "(?<=(tel:))[\\S\\s]*?(?=(,))").Value;
                string zip = Regex.Match(sList, "(?<=(zip:))[\\S\\s]*?(?=(,))").Value;
                string type = Regex.Match(sList, "(?<=(poiType:))[\\S\\s]*?(?=(,))").Value;
                string uid = Regex.Match(sList, "(?<=(uid:))[\\S\\s]*?(?=(,))").Value;
                string pointX = Regex.Match(sList, "(?<=(x:))[\\S\\s]*?(?=(,))").Value;
                string pointY = Regex.Match(sList, "(?<=(y:))[\\S\\s]*?(?=(},))").Value;

                this.BeginInvoke((MethodInvoker)delegate()
                {
                    this.liMessage.Items.Add(name + ";" + address);
                });

                if (!StringProcess.IsNullOrEmpty(name) && (city.Trim() == this.txtCity.Text.Trim() || city.Trim() == this.txtCity.Text.Trim().Remove(this.txtCity.Text.Trim().Length - 1)))
                    sqlOP.Insert("name,address,city,district,street,street_number,business,tel,zip,type,uid,pointX,pointY,cX,cY", "POI", "'" + name + "','" + address + "','" + city + "','" + district + "','" + street + "','" + street_number + "','" + business + "','" + tel + "','" + zip + "','" + type + "','" + uid + "','" + pointX + "','" + pointY + "','" + cX + "','" + cY + "'");
            }

            sqlOP.DeleteRepeat("uid", "POI", "id");
            //sqlOP.DeleteRepeat("name,address", "POI", "id");
        }

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            sqlOP.db.Close();
            System.Environment.Exit(System.Environment.ExitCode);
            this.Dispose();
            this.Close();
        }

        private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ShowMainForm();
        }

        void ShowMainForm()
        {
            this.Visible = true;

            if (this.WindowState == FormWindowState.Minimized)
                this.WindowState = FormWindowState.Normal;

        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                this.Visible = false;
                e.Cancel = true;
            }
            else
                this.notifyIcon.Visible = false;
        }

        private void MainForm_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Visible = false;
            }
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            this.btnStart.Enabled = false;
            Thread thread = new Thread(new ThreadStart(AliasStart));
            thread.Start();
        }

        void AliasStart()
        {
            string name = "";
            sqlOP.db.Open();
            DataTable dtAlias = sqlOP.Select("id,name,pointX,pointY", "POI", "");

            foreach (DataRow drAlias in dtAlias.Rows)
            {
                id = Convert.ToInt32(drAlias["id"].ToString().Trim());
                name = drAlias["name"].ToString().Trim();
                string url = "http://map.baidu.com/su?wd=" + HttpUtility.UrlEncode(name) + "&cid=1&type=0";

                this.BeginInvoke((MethodInvoker)delegate()
                {
                    int count = dtAlias.Rows.Count;
                    this.liMessage.Items.Add("正在更新:" + name);
                    this.progressBar.Minimum = 0;
                    this.progressBar.Maximum = count;
                    this.progressBar.Step = 1;
                    this.progressBar.PerformStep();
                    this.lbResult.Text = string.Format("当前位置：{0}/{1}", k, count);
                });

                try
                {
                    AddAlias(url);
                }
                catch (Exception ex)
                {
                    sqlOP.Insert("x,y,time", "log", "'" + drAlias["pointX"].ToString() + "','" + drAlias["pointY"].ToString() + "','" + DateTime.Now.ToString() + "'");
                }
            }

            sqlOP.db.Close();

            this.BeginInvoke((MethodInvoker)delegate()
            {
                MessageBox.Show("信息更新完成！");
                this.btnStart.Enabled = true;
            });
        }

        void AddAlias(string url)
        {
            string aliasInfo = StringProcess.GetResult(url, Encoding.UTF8).Replace("\"", "").Replace("\\'","");
            string aliasContent = Regex.Match(aliasInfo, "(?<=(s:\\[))[\\S\\s]*?(?=(\\]))").Value;

            char[] delimiterChars = { ',', '，' };
            string[] sAlias = StringProcess.SplitString(aliasContent, delimiterChars);

            foreach (string alias in sAlias)
            {
                if (StringProcess.IsContain(alias, this.txtCity.Text))
                {
                    string aliasName = alias.Replace("$", "").Replace("332", "");
                    char[] delimiter = { '$' };
                    string[] c = StringProcess.SplitString(alias, delimiter);

                    string aliasCity = c[0];
                    string aliasDistrict = c[1];
                    string aliasStreet = c[2];

                    sqlOP.Insert("aliasName,city,district,street,poiID", "Alias", "'" + aliasName + "','" + aliasCity + "','" + aliasDistrict + "','" + aliasStreet + "','" + id + "'");
                }
            }

            ++k;
        }

        private void btnReAliasQuery_Click(object sender, EventArgs e)
        {
            sqlOP.db.Open();
            DataTable dtReAlias = sqlOP.Select("id,x,y", "log", "");

            foreach (DataRow drReAlias in dtReAlias.Rows)
            {
                DataTable dtPOI = sqlOP.Select("id,name,pointX,pointY", "POI", "(pointX = N'" + drReAlias["x"].ToString() + "') AND (pointY = N'" + drReAlias["y"].ToString() + "')");
                string reName = dtPOI.Rows[0]["name"].ToString().Trim();
                id = Convert.ToInt32(dtPOI.Rows[0]["id"].ToString().Trim());

                string reUrl = "http://map.baidu.com/su?wd=" + HttpUtility.UrlEncode(reName) + "&cid=1&type=0";

                this.BeginInvoke((MethodInvoker)delegate()
                {
                    this.liMessage.Items.Add("正在更新:" + reName);
                });

                AddAlias(reUrl);
                sqlOP.Delete("log", "(id = " + drReAlias["id"].ToString() + ")");
            }

            sqlOP.db.Close();
            MessageBox.Show("查漏完成！");
        }

        private void btnUpdateAddress_Click(object sender, EventArgs e)
        {
            this.btnUpdateAddress.Enabled = false;
            Thread thread = new Thread(new ThreadStart(UpdateInfo));
            thread.Start();
        }

        void UpdateInfo()
        {
            sqlOP.db.Open();
            UpdateDistrict();
            UpdateAddress();
            sqlOP.db.Close();

            this.BeginInvoke((MethodInvoker)delegate()
            {
                MessageBox.Show("地址信息更新完成！");
                this.btnUpdateAddress.Enabled = true;
            });
        }

        void UpdateDistrict()
        {
            k = 1;
            DataTable dtAliasDistrict = sqlOP.Select("poiID", "Alias", "district = ' '");
            int countDistrict = dtAliasDistrict.Rows.Count;

            foreach (DataRow rowAlisaDistrict in dtAliasDistrict.Rows)
            {
                this.BeginInvoke((MethodInvoker)delegate()
                {
                    this.progressBar.Minimum = 0;
                    this.progressBar.Maximum = countDistrict;
                    this.progressBar.Step = 1;
                    this.progressBar.PerformStep();
                    this.lbResult.Text = string.Format("当前位置：{0}/{1}", k, countDistrict);
                });

                string poiID = rowAlisaDistrict["poiID"].ToString().Trim();
                DataTable dtPOIDistrict = sqlOP.Select("district", "POI", "(id = " + poiID + ")");

                if (countDistrict != 0)
                {
                    string district = dtPOIDistrict.Rows[0]["district"].ToString().Trim();

                    if (!StringProcess.IsNullOrEmpty(district))
                    {
                        sqlOP.Update("district", "Alias", "(poiID = " + poiID + ")", district);
                    }
                }

                ++k;
            }
        }

        void UpdateAddress()
        {
            k = 1;
            DataTable dtAliasStreet = sqlOP.Select("poiID,district", "Alias", "street = ' '");
            int countStreet = dtAliasStreet.Rows.Count;

            foreach (DataRow rowAlisaStreet in dtAliasStreet.Rows)
            {
                string poiID = rowAlisaStreet["poiID"].ToString().Trim();
                string districtAlisa = rowAlisaStreet["district"].ToString().Trim();
                DataTable dtPOIStreet = sqlOP.Select("district,street,street_number", "POI", "(id = " + poiID + ")");

                this.BeginInvoke((MethodInvoker)delegate()
                {
                    this.progressBar.Minimum = 0;
                    this.progressBar.Maximum = countStreet;
                    this.progressBar.Step = 1;
                    this.progressBar.PerformStep();
                    this.lbResult.Text = string.Format("当前位置：{0}/{1}", k, countStreet);
                });

                if (countStreet != 0)
                {
                    string street = dtPOIStreet.Rows[0]["street"].ToString().Trim();
                    string streetNum = dtPOIStreet.Rows[0]["street_number"].ToString().Trim();
                    string districtPOI = dtPOIStreet.Rows[0]["district"].ToString().Trim();

                    if (!StringProcess.IsNullOrEmpty(street) && districtAlisa == districtPOI)
                    {
                        sqlOP.Update("street", "Alias", "(poiID = " + poiID + ")", street + streetNum);
                    }
                }

                ++k;
            }
        }

        private void btnChange_Click(object sender, EventArgs e)
        {
            this.btnChange.Enabled = false;
            Thread thread = new Thread(new ThreadStart(Get));
            thread.Start();
            MessageBox.Show("完成！");
            this.btnChange.Enabled = true;
        }

        [DllImport("user32.dll", EntryPoint = "FindWindow", CharSet = CharSet.Auto)]
        private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int PostMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);

        public const int WM_CLOSE = 0x10;

        private void StartKiller()
        {
            System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
            timer.Interval = 100; //启动时间
            timer.Tick += new EventHandler(Timer_Tick);
            timer.Start();
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            KillMessageBox();
            //停止Timer
            ((System.Windows.Forms.Timer)sender).Stop();
        }


        private void KillMessageBox()
        {
            //按照MessageBox的标题，找到MessageBox的窗口
            IntPtr ptr = FindWindow(null, "MessageBox");
            if (ptr != IntPtr.Zero)
            {
                //找到则关闭MessageBox窗口
                PostMessage(ptr, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
            }
        }


        void Get()
        {
            k = 1;
            sqlOP.db.Open();

            DataTable dtJW = sqlOP.Select("id,pointX,pointY", "POI", "lng is not null");
            int countStreet = dtJW.Rows.Count;
            MessageBox.Show(countStreet.ToString());
            foreach (DataRow rowJW in dtJW.Rows)
            {

                string pointID = rowJW["id"].ToString().Trim();
                string pointJ = rowJW["pointX"].ToString().Trim();
                string pointW = rowJW["pointY"].ToString().Trim();

                try
                {
                    getWeb = new WebBrowser();
                    
                    string document = "<html><script type=\"text/javascript\" src=\"http://api.map.baidu.com/api?v=1.2\"></script><body><div id = \"container\"></div></body></html>" +
                        "<script type=\"text/javascript\">" +
                        "var map = new BMap.Map(\"container\");" +
                        "map.clearOverlays();" +
                        "var mctXY = new BMap.Pixel(\"" + pointJ + "\",\"" + pointW + "\");" +
                        "var projection2 = map.getMapType().getProjection();" +
                        "var LngLat = projection2.pointToLngLat(mctXY);" +
                        "document.write(\"<p id = 'poi'>\" + LngLat.lng + \",\" + LngLat.lat + \",\" + \"</p>\");" +
                        "</script>";
                    getWeb.DocumentText = document;
                    
                    StartKiller();
                    MessageBox.Show(k.ToString(), "MessageBox");
                    
                    string jwPoint = getWeb.Document.GetElementById("poi").InnerText;
                    
                    char[] c = { ',' };
                    string[] JW = StringProcess.SplitString(jwPoint, c);
                    sqlOP.Update("lng,lat", "POI", "id = " + pointID, JW[0].Trim() + "," + JW[1].Trim());
                    Thread.Sleep(100);
                    //GC.Collect();
                }
                catch (Exception ex)
                {
                    continue;
                }

                ++k;
            }

            sqlOP.db.Close();
        }

        private void btnFBName_Click(object sender, EventArgs e)
        {
            this.btnFBName.Enabled = false;
            Thread thread = new Thread(new ThreadStart(SelectFB));
            thread.Start();
        }

        void SelectFB()
        {
            k = 1;
            sqlOP.db.Open();
            DataTable dtFB = sqlOP.Select("id,lng,lat", "POI", "fbName IS NULL");
            foreach (DataRow drFB in dtFB.Rows)
            {
                id = Convert.ToInt32(drFB["id"].ToString().Trim());
                string fbLng = drFB["lng"].ToString().Trim();
                string fbLat = drFB["lat"].ToString().Trim();

                this.BeginInvoke((MethodInvoker)delegate()
                {
                    int count = dtFB.Rows.Count;
                    this.progressBar.Minimum = 0;
                    this.progressBar.Maximum = count;
                    this.progressBar.Step = 1;
                    this.progressBar.PerformStep();
                    this.lbResult.Text = string.Format("当前位置：{0}/{1}", k, count);
                });

                DataTable dtName = mysqlOP.GetName(fbLng, fbLat);

                if (dtName.Rows.Count != 0)
                {
                    string fbName = dtName.Rows[0]["name"].ToString();
                    sqlOP.Update("fbName", "POI", "id = " + id.ToString(), fbName);
                }

                ++k;
            }

            sqlOP.db.Close();

            this.BeginInvoke((MethodInvoker)delegate()
            {
                MessageBox.Show("信息更新完成！");
                this.btnFBName.Enabled = true;
            });
        }

        void Change()
        {
            sqlOP.db.Open();
            DataTable dtPoint = sqlOP.Select("id,aliasName,poiID", "Alias", "lng = ' '");

            foreach (DataRow drPoint in dtPoint.Rows)
            {
                id = Convert.ToInt32(drPoint["id"].ToString().Trim());
                string poiID = drPoint["poiID"].ToString().Trim();
                DataTable dtPoi = sqlOP.Select("name", "POI", "id = " + poiID);
                string name = dtPoi.Rows[0]["name"].ToString();
                //string name = drPoint["aliasName"].ToString().Trim();

                this.BeginInvoke((MethodInvoker)delegate()
                {
                    int count = dtPoint.Rows.Count;
                    this.progressBar.Minimum = 0;
                    this.progressBar.Maximum = count;
                    this.progressBar.Step = 1;
                    this.progressBar.PerformStep();
                    this.lbResult.Text = string.Format("当前位置：{0}/{1}", k, count);
                });

                try
                {
                    string jwUrl = "http://api.map.baidu.com/geocoder?address=" + HttpUtility.UrlEncode(name);
                    string jwInfo = StringProcess.GetResult(jwUrl, Encoding.UTF8).Replace("\"", "").Replace("\\'", "").Replace("\n", "").Replace("\t", "").Replace("\r", "");
                    string lat = Regex.Match(jwInfo, "(?<=(lat>))[\\S\\s]*?(?=(<))").Value;
                    string lng = Regex.Match(jwInfo, "(?<=(lng>))[\\S\\s]*?(?=(<))").Value;
                    sqlOP.Update("lng,lat", "Alias", "id = " + id.ToString(), lng + ", " + lat);
                    ++k;
                }
                catch (Exception ex)
                {
                    //sqlOP.Insert("x,y,time", "log", "'" + drPoint["pointX"].ToString() + "','" + drPoint["pointY"].ToString() + "','" + DateTime.Now.ToString() + "'");
                }
            }

            sqlOP.db.Close();

            this.BeginInvoke((MethodInvoker)delegate()
            {
                MessageBox.Show("信息更新完成！");
                this.btnChange.Enabled = true;
            });
        }

        private void btnAreaPoints_Click(object sender, EventArgs e)
        {
            this.btnAreaPoints.Enabled = false;
            OpenFile();

            Thread thread = new Thread(new ThreadStart(UpdateAreaPoints));
            thread.Start();
        }

        void OpenFile()
        {
            OpenFileDialog openFile = new OpenFileDialog();
            openFile.Filter = "xls文件|*.xls|xlsx文件|*.xlsx|所有文件|*.*";
            openFile.FilterIndex = 1;

            if (openFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                dtColor = ExcelOperate.LoadDataFromExcel(openFile.FileName, "Sheet1").Tables[0];
            }
        }

        void UpdateAreaPoints()
        {
            k = 1;
            mysqlOP.conn.Open();
            DataTable dtAreaPoints = mysqlOP.SelectAll();
            foreach (DataRow drAreaPoints in dtAreaPoints.Rows)
            {
                id = Convert.ToInt32(drAreaPoints["id"].ToString().Trim());
                string region = drAreaPoints["region"].ToString().Trim();
                string name = drAreaPoints["name"].ToString().Trim();
                
                this.BeginInvoke((MethodInvoker)delegate()
                {
                    int count = dtAreaPoints.Rows.Count;
                    this.progressBar.Minimum = 0;
                    this.progressBar.Maximum = count;
                    this.progressBar.Step = 1;
                    this.progressBar.PerformStep();
                    this.lbResult.Text = string.Format("当前位置：{0}/{1}", k, count);
                });

                string areaPoints = region.Replace("POLYGON((", "").Replace("))", "").Replace(", ", ";").Replace(" ", ", ");
                string areaColor = dtColor.Select("name LIKE '%" + name + "%'")[0].ItemArray[1].ToString().Trim();
                mysqlOP.UpdateArea(id.ToString(), areaPoints, areaColor);
                
                ++k;
            }

            mysqlOP.conn.Close();

            this.BeginInvoke((MethodInvoker)delegate()
            {
                MessageBox.Show("信息更新完成！");
                this.btnAreaPoints.Enabled = true;
            });
        }
    }
}
